package com.banmao.greedysnake.vo;

import javafx.scene.paint.Color;
import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;
import java.util.function.Predicate;
import java.util.stream.Collectors;

// 食物
@Data
public class Food {

    private Double foodX;
    private Double foodY;
    private Double foodSize;
    private Color foodColor;

    private static Random random = new Random();

    private Food() {}

    // 随机生成food坐标
    public static Food generateFood(Snake snake) {

        double[] position = getRandomXY();

        //double nextDobleX = (headX + random.nextDouble(350)) * Math.pow(-1., random.nextInt(1, 3));
        //double nextDobleY = (headY + random.nextDouble(350)) * Math.pow(-1., random.nextInt(1, 3));

        List<Snake.Body> bodies = snake.getBodies();
        boolean hasRepeat = true;

        while (hasRepeat) {
            double[] finalPosition = position;
            List<Snake.Body> collect = bodies.stream().filter(new Predicate<Snake.Body>() {
                @Override
                public boolean test(Snake.Body body) {
                    // X Y坐标都相同，返回true
                    return Double.compare(body.getX(), finalPosition[0]) == 0
                            && Double.compare(body.getY(), finalPosition[1]) == 0;
                }
            }).toList();
            if(CollectionUtils.isEmpty(collect)) {
                hasRepeat = false;
            } else {
                position = getRandomXY();
            }
        }

        double nextDoubleX = position[0];
        double nextDoubleY = position[1];

        if(nextDoubleX < 0) {
            nextDoubleX = 0.;
        } else if (nextDoubleX > Constants.CANCAS_WIDTH - Constants.POINT_SIZE) {
            nextDoubleX = Constants.CANCAS_WIDTH - Constants.POINT_SIZE;
        }
        if(nextDoubleY < 0) {
            nextDoubleY = 0.;
        } else if (nextDoubleY > Constants.CANCAS_HEIGHT - Constants.POINT_SIZE) {
            nextDoubleY = Constants.CANCAS_HEIGHT - Constants.POINT_SIZE;
        }

        Food food = new Food();
        food.setFoodX(nextDoubleX);
        food.setFoodY(nextDoubleY);
        food.setFoodSize(Constants.POINT_SIZE);
        food.setFoodColor(Color.ROYALBLUE);

        return food;
    }

    private static double[] getRandomXY() {
        int widthDiv = (int) (Constants.CANCAS_WIDTH / Constants.POINT_SIZE);
        int heightDiv = (int) (Constants.CANCAS_HEIGHT / Constants.POINT_SIZE);

        double nextDoubleX = random.nextInt(widthDiv) * Constants.POINT_SIZE;
        double nextDoubleY = random.nextInt(heightDiv) * Constants.POINT_SIZE;
        return new double[] {nextDoubleX, nextDoubleY};
    }

}
